﻿using System;
using System.Data;
using System.Text;
using Ue.Qcdz.Domain.TreeViews;

namespace Ue.Qcdz.Repositories.TreeViews
{
    public class TreeNodeWhereClause : Ue.Infrastructure.RepositoryFramework.Repository.IWhereClause
    {
        private IDataParameter treeViewParameter;
        private IDataParameter parentParameter;

        public TreeNodeWhereClause(ITreeNodeDataQuery nodeDataQuery)
            : this(nodeDataQuery.TreeView, nodeDataQuery.Parent) { }

        public TreeNodeWhereClause(TreeView treeView, TreeNode parentNode)
        {
            this.treeViewParameter = SqlServerDriver.Instance.BuildParameter(
                TreeNodeFactory.FieldNames.TreeViewInNodes,
                treeView == null ? null : treeView.Key);

            this.parentParameter = SqlServerDriver.Instance.BuildParameter(
                TreeNodeFactory.FieldNames.ParentId,
                parentNode == null ? null : parentNode.Key);
        }

        public string Clause
        {
            get
            {
                StringBuilder builder = new StringBuilder();

                builder.Append(string.Format(
                    "{0}=@{0} and ",
                    TreeNodeFactory.FieldNames.TreeViewInNodes));

                builder.Append(string.Format(
                    this.parentParameter.Value == DBNull.Value ? "{0} is null" : "{0}=@{0}",
                    TreeNodeFactory.FieldNames.ParentId));

                return builder.ToString();
            }
        }

        public IDataParameter[] Parameters
        {
            get
            {
                return new IDataParameter[]{
                    this.treeViewParameter,
                    this.parentParameter
                };
            }
        }
    }
}
